package com.telit.common.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendBatchSmsResponse;
import com.telit.common.config.SmsAliServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;


/**
 * @author yuzhanxiang
 * @description: 短信工具类
 * @copyright 天立泰科技股份有限公司
 * @since 2022/4/1 16:31
 **/
@Component
@Slf4j
public class SmsUtils implements ApplicationListener<ContextRefreshedEvent> {

    private static final String BEAN_NAME = "smsClient";
    private static final String PROP_BEAN_NAME = "smsAliServerConfig";

    private static AsyncClient client;
    private static SmsAliServerConfig smsAliServerConfig;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        client = (AsyncClient) event.getApplicationContext().getBean(BEAN_NAME);
        smsAliServerConfig = (SmsAliServerConfig) event.getApplicationContext().getBean(PROP_BEAN_NAME);
    }


    /**
     * 给手机号发送短信验证码
     *
     * @param mobiles      电话号码 批量
     * @param templateCode 短信模板编码
     * @param param        传入短信参数
     */
    public static void sendContent(List<String> mobiles, String templateCode, Object param) throws ExecutionException, InterruptedException {
        mobiles = CheckSmsPhoneUtil.checkPhone(mobiles);
        if (CollectionUtil.isEmpty(mobiles)) {
            log.info("==============" + "手机号被过滤为空");
            return;
        }
        log.info("==============手机号" + JSONUtil.toJsonStr(mobiles));
        final String signNameJson = JSONUtil.toJsonStr(
                mobiles.stream().map(n -> smsAliServerConfig.getSignName()).collect(Collectors.toList()));
        final String paramJson = JSONUtil.toJsonStr(mobiles.stream().map(n -> param).collect(Collectors.toList()));
        final SendBatchSmsRequest request = SendBatchSmsRequest.builder()
                .phoneNumberJson(JSONUtil.toJsonStr(mobiles))
                .signNameJson(signNameJson)
                .templateCode(templateCode)
                .templateParamJson(paramJson)
                .build();
        final CompletableFuture<SendBatchSmsResponse> response = client.sendBatchSms(request);
        log.info("==============结果" + JSONUtil.toJsonStr(response.get()));
    }
}
